package com.dylan.shot.head.shiro;

import com.dylan.shot.common.model.Member;
import com.dylan.shot.head.service.MemberAuthenticateService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationListener;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * Created by Dylan on 2017/9/12.
 */
public class MyAuthenticationListener implements AuthenticationListener {
    private Logger LOG = LoggerFactory.getLogger(getClass());

    @Autowired
    private MemberAuthenticateService memberAuthenticateService;

    @Override
    public void onSuccess(AuthenticationToken authenticationToken, AuthenticationInfo authenticationInfo) {
        if (authenticationInfo instanceof MySimpleAuthenticationInfo) {
            Member member = ((MySimpleAuthenticationInfo) authenticationInfo).getMember();
            LOG.info("登录成功:{}", member.getMemberId());

            // 保存用户信息到session
            ShiroHelper.setCachedMember(member);

            // 更改最近登录时间
            Member up = new Member();
            up.setMemberId(member.getMemberId());
            up.setLatestLoginTime(new Date());
            memberAuthenticateService.updateMemberByMemberId(up);
        } else {
            LOG.info("登录成功:{}", authenticationInfo.getPrincipals().toString());
        }
    }

    @Override
    public void onFailure(AuthenticationToken authenticationToken, AuthenticationException e) {

    }

    @Override
    public void onLogout(PrincipalCollection principalCollection) {
        ShiroHelper.removeCachedMember();
    }
}
